package cn.datawin.bms.modules.customer.service.impl;

import cn.datawin.bms.customer.entity.CstmCustomerEntity;
import cn.datawin.bms.customer.entity.CstmCustomerProviderChannelEntity;
import cn.datawin.bms.customer.redis.CstmCustomerProviderChannelRedisDto;
import cn.datawin.bms.customer.vo.CstmCustomerProviderChannelVo;
import cn.datawin.bms.modules.customer.mapper.CstmCustomerProviderChannelMapper;
import cn.datawin.bms.modules.customer.service.CstmCustomerProviderChannelService;
import cn.datawin.bms.modules.customer.service.CstmCustomerService;
import cn.datawin.bms.modules.provider.service.ProvProviderChannelService;
import cn.datawin.bms.provider.entity.ProvProviderChannelEntity;
import cn.datawin.bms.provider.entity.ProvProviderEntity;
import cn.datawin.common.core.util.RedisUtils;
import cn.datawin.constant.RedisPattern;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 下游客户上游供应商通道绑定
 *
 * @author datawin-sms
 * @date 2025-09-06 15:30:45
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class CstmCustomerProviderChannelServiceImpl extends ServiceImpl<CstmCustomerProviderChannelMapper, CstmCustomerProviderChannelEntity> implements CstmCustomerProviderChannelService {

	private final CstmCustomerService cstmCustomerService;
	private final ProvProviderChannelService providerChannelService;

	@Override
	public List<CstmCustomerProviderChannelEntity> getProviderChannels(Long customerId) {
		return baseMapper.selectList(new LambdaQueryWrapper<CstmCustomerProviderChannelEntity>().eq(CstmCustomerProviderChannelEntity::getCustomerId, customerId));
	}

	@Override
	public boolean bindProviderChannel(List<CstmCustomerProviderChannelEntity> channelList) {
		if (CollUtil.isEmpty(channelList)) {
			return false;
		}

		return false;
	}

	@Override
	public Page<CstmCustomerProviderChannelVo> customPage(Page<CstmCustomerProviderChannelVo> page, CstmCustomerProviderChannelEntity cstmCustomerProviderChannel) {
		// 1. 先查询主表数据
		LambdaQueryWrapper<CstmCustomerProviderChannelEntity> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(CstmCustomerProviderChannelEntity::getCustomerId, cstmCustomerProviderChannel.getCustomerId());
		List<CstmCustomerProviderChannelEntity> entities = baseMapper.selectList(queryWrapper);
		if(CollUtil.isEmpty(entities)){
			return page;
		}

		// 2. 收集所有customerId和providerChannelId
		Set<Long> customerIds = entities.stream()
				.map(CstmCustomerProviderChannelEntity::getCustomerId)
				.collect(Collectors.toSet());
		Set<Long> channelIds = entities.stream()
				.map(CstmCustomerProviderChannelEntity::getProviderChannelId)
				.collect(Collectors.toSet());

		// 3. 批量查询关联表数据
		//根据id获取cstm_customer数据
		List<CstmCustomerEntity> customerList = cstmCustomerService.list(Wrappers.lambdaQuery(CstmCustomerEntity.class).in(CstmCustomerEntity::getId, customerIds));
		Map<Long, String> customerNameMap = customerList.stream().collect(Collectors.toMap(CstmCustomerEntity::getId, CstmCustomerEntity::getName));
		//根据id获取prov_provider_channel数据
		List<ProvProviderChannelEntity> channelList = providerChannelService.list(Wrappers.lambdaQuery(ProvProviderChannelEntity.class).in(ProvProviderChannelEntity::getId, channelIds));
		Map<Long, String> channelNameMap = channelList.stream().collect(Collectors.toMap(ProvProviderChannelEntity::getId, ProvProviderChannelEntity::getChannelName));

		// 4. 组装DTO结果
		List<CstmCustomerProviderChannelVo> result = entities.stream().map(entity -> {
			CstmCustomerProviderChannelVo dto = new CstmCustomerProviderChannelVo();
			BeanUtils.copyProperties(entity, dto);
			dto.setCustomerName(customerNameMap.get(entity.getCustomerId()));
			dto.setProviderChannelName(channelNameMap.get(entity.getProviderChannelId()));
			return dto;
		}).collect(Collectors.toList());
		page.setRecords(result);
		return page;
	}

    @Override
    public boolean saveChannel(CstmCustomerProviderChannelEntity entity) {
		boolean b = SqlHelper.retBool(baseMapper.insert(entity));
		if(b){
			//更新绑定通道的缓存
			updateCache(entity.getCustomerId());
			return false;
		}
		return false;
    }

	@Override
	public boolean updateChannel(CstmCustomerProviderChannelEntity cstmCustomerProviderChannel) {
		boolean b = SqlHelper.retBool(baseMapper.updateById(cstmCustomerProviderChannel));
		if(b){
			//更新绑定通道的缓存
			updateCache(cstmCustomerProviderChannel.getCustomerId());
			return false;
		}
		return false;
	}

	@Override
	public boolean removeChannel(ArrayList<Long> toList) {
		if(CollUtil.isEmpty(toList)){
			return false;
		}
		//查询第一条数据，获取用户id
		CstmCustomerProviderChannelEntity entity = baseMapper.selectById(toList.get(0));
		//删除数据库数据
		boolean b = SqlHelper.retBool(baseMapper.deleteBatchIds(toList));
		if(b){
			//更新绑定通道的缓存
			updateCache(entity.getCustomerId());
			return false;
		}
		return false;
	}

	private void updateCache(Long customerId) {
		//查询用户绑定的所有通道
		String rKey = String.format(RedisPattern.CSTM_CUSTOMER_PROVIDER_CHANNEL_CACHE, customerId);
		List<CstmCustomerProviderChannelEntity> channelList = getProviderChannels(customerId);
		if(CollUtil.isEmpty(channelList)){//通道为空，删除原有的缓存
			//删除原有的缓存
			RedisUtils.del(rKey);
			return;
		}
		//转换为缓存对象
		List<CstmCustomerProviderChannelRedisDto> cacheList = channelList.stream().map(entity -> {
			CstmCustomerProviderChannelRedisDto dto = new CstmCustomerProviderChannelRedisDto();
			BeanUtils.copyProperties(entity, dto);
			return dto;
		}).toList();
		//更新缓存
		//先删除原有的缓存
		RedisUtils.del(rKey);
		//再设置新的缓存
		RedisUtils.lRPAll(rKey,cacheList);
//		List<CstmCustomerProviderChannelRedisDto> dtos = RedisUtils.lGet(rKey, 0, -1);
//		log.info(JSON.toJSONString(dtos));
	}
}
